<?php

namespace App\Models;

use App\Service\BangCache;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Str;

class BaseUser extends Base
{

    // 缓存字段，用于搜索绑定的字段
    protected $cacheFields = ['id'];


    // 获取图片
    protected function getHeadImgAttribute($value)
    {
        if($value){
            return $this->replaceDomain($value, 'full');
        }

        // 如果没头像 则获取默认头像
        if(empty($row['sex'])){
            return '';
        }

        // 如果是男的
        if($row['sex'] == 1){
            return '/static/avatar_1.png';
        }

        // 如果是女的 保密的
        return '/static/avatar_2.png';
    }

    // 保存图片
    protected function setHeadImgAttribute($value)
    {
        return $this->replaceDomain($value, 'old');
    }


    // 检查唯一性
    public function checkUser($data, $id = '')
    {
        $where = [];
        // username 唯一性
        if(!empty($data['username'])){
            $yzwhere = [['username', '=', $data['username']]];
            if($id){
                $where = [['id', '<>', $id]];
            }
            $info = $this->newQuery()->where($where)->where($yzwhere)->first();
            if($info){
                //return $this->return_false('该用户名已经存在！');
                return $this->return_false('loginname_has_exist');
            }
        }

        // email 唯一性
        if(!empty($data['email'])){
            $yzwhere = [['email', '=', $data['email']]];
            if($id){
                $where = [['id', '<>', $id]];
            }
            $info = $this->newQuery()->where($where)->where($yzwhere)->first();
            if($info){
                //return $this->return_false('该邮箱已经存在！');
                return $this->return_false('email_has_exist');
            }
        }

        // mobile 唯一性
        if(!empty($data['mobile'])){
            $yzwhere = [['mobile', '=', $data['mobile']]];
            if($id){
                $where = [['id', '<>', $id]];
            }
            $info = $this->newQuery()->where($where)->where($yzwhere)->first();
            if($info){
                //return $this->return_false('该手机号已经存在！');
                return $this->return_false('mobile_has_exist');
            }
        }

        // 整理角色
        if(empty($data['role'])){
            unset($data['role']);
        } else{
            if(is_string($data['role'])){
                return $this->return_false('权限为数组！');
            }

            // 整理
            $roles = [];
            foreach($data['role'] as $_role){
                if(empty($_role['role'])){
                    continue;
                }
                $roles[] = $_role['role'];
            }
            $data['role'] = json_encode($roles, 1);
        }

        return $data;
    }

    // 添加验证
    public function checkData($data, $where = [])
    {
        // 随机码
        // 修改的时候，没有传递密码 则不修改密码
        if($where && empty($data['password'])){
            unset($data['password']);
        } else{
            // 不是修改的时候 没有传递密码，默认为123456
            $salt = Str::random(4);
            if(empty($data['password'])){
                $data['password'] = 123456;
            }

            // 密码
            $data['salt']     = $salt;
            $data['password'] = $this->add_md5($data['password'], $salt);
        }

        return $data;
    }

    // 登录
    public function login($username, $password, $loginField = 'username')
    {
        // 获取用户信息
        $field = $this->loginField();
        $info  = $this->newQuery()->where([$loginField => $username])->select($field)->first(); // ->recycle()
        if(empty($info)){
            //return $this->return_false('用户不存在！！');
            return $this->return_false('user_has_no_exist');
        }
        if($info->status === 0){
            //return $this->return_false('用户被禁止登录！！');
            return $this->return_false('user_is_disabled');
        }


        // 验证密码
        $info    = $info->toArray();
        $isCheck = $this->ckeckPassword($password, $info['salt'], $info['password']);
        if(!$isCheck){
            //return $this->return_false('密码错误！！');
            return $this->return_false('password_is_wrong');
        }


        // 如果有最后一次的登录信息
        if(isset($info['last_ip']) && isset($info['last_time'])){
            $onlineip = request()->ip();
            $updata   = ['last_ip' => $onlineip, 'last_time' => LARAVEL_TIME,];
            DB::beginTransaction();
            try{
                $rst = $this->newQuery()->where('id', $info['id'])->update($updata);
                // 提交事务
                DB::commit();
            } catch(\Exception $e){
                // 回滚事务
                DB::rollback();

                return $this->return_false($e->getMessage(), 400);
            }

            // 删除缓存
            $this->deleteCacheShow($info);
        }

        // 如果有权限
        // 登录成功
        //$user = ['id' => $info->id, 'username' => $info->username, 'mobile' => $info->mobile, 'time' => LARAVEL_TIME,];
        if(!empty($info['role'])){
            $info['role'] = is_string($info['role']) ? json_decode($info['role']) : $info['role'];
        }

        return $info;
    }

    // 注册
    public function reg($username, $password, $loginField = 'username')
    {
        // 获取用户信息
        $field = ['id', 'status'];
        $info  = $this->newQuery()->where([$loginField => $username])->select($field)->first(); // ->recycle()
        if(!empty($info)){
            //return $this->return_false('用户已经存在！！');
            return $this->return_false('loginname_has_exist');
        }

        // 密码
        $salt     = Str::random(4);
        $password = $this->add_md5($password, $salt);

        // 数组
        $data = [
            'status'    => 1,
            'salt'      => $salt,
            'password'  => $password,
            $loginField => $username,
            'reg_ip'    => request()->ip(),
            'reg_time'  => LARAVEL_TIME,
        ];

        // 保存
        $this->fill($data);
        $result = $this->save();

        // 缓存操作
        $this->deleteCacheShow($data);

        // 登录成功
        $user = ['id' => $this->id, $loginField => $username, 'time' => LARAVEL_TIME,];

        return $user;
    }

    // 登录的字段
    protected function loginField()
    {
        return ['id', 'username', 'password', 'salt', 'status', 'mobile', 'nickname',];
    }

    // 加密密码
    public function add_md5($password, $salt = '')
    {
        return password_hash($password.$salt, PASSWORD_DEFAULT);
    }

    // 解密
    public function ckeckPassword($password, $salt, $hash)
    {
        return password_verify($password.$salt, $hash);
    }

}
